package link.chengguo.orangemall.delivery.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import link.chengguo.orangemall.ApiContext;
import link.chengguo.orangemall.shms.entity.ShmsShopInfo;
import link.chengguo.orangemall.service.shms.IShmsShopInfoService;
import link.chengguo.orangemall.util.JwtTokenUtil;
import link.chengguo.orangemall.utils.ValidatorUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author yzb
 * @ClassName: BaseAction
 * @Description: 基础控制类
 */
@Slf4j
public class BaseAction {

    @Resource
    protected JwtTokenUtil jwtTokenUtil;
    @Autowired
    protected ApiContext apiContext;
    @Resource
    protected IShmsShopInfoService shopInfoService;

    /**
     * 得到request对象
     */
    @Autowired
    protected HttpServletRequest request;
    /**
     * 得到response对象
     */
    @Resource
    protected HttpServletResponse response;

    /**
     * 获取token
     * @return token
     */
    public String getToken() {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        String requestType = request.getMethod();
        if ("OPTIONS".equals(requestType)) {
            return null;
        }
        String tokenPre = "authorization1";
        String authHeader = request.getParameter(tokenPre);
        if (ValidatorUtils.empty(authHeader)) {
            authHeader = request.getHeader(tokenPre);
        }
        return authHeader;
    }

    /**
     * 获取接口编码
     * @return code
     */
    public String getInterfaceCode() {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        String requestType = request.getMethod();
        if ("OPTIONS".equals(requestType)) {
            return null;
        }
        String code = "interfaceCode";
        String authHeader = request.getParameter(code);
        if (ValidatorUtils.empty(authHeader)) {
            authHeader = request.getHeader(code);
        }
        return authHeader;
    }

    /**
     * 查询商家信息
     * @return code
     */
    public ShmsShopInfo getShopInfo() {
        //token查询商家
        String token=this.getToken();
        ShmsShopInfo shopInfo=shopInfoService.getOne(new QueryWrapper<ShmsShopInfo>().eq("token",token));
        if (shopInfo==null){
            throw new RuntimeException("未找到店铺信息");
        }
        return shopInfo;
    }

}
